<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\AdminActionTypeEnum;
use App\Exceptions\ApiException;
use App\Format\CompanyMessageFormat;
use App\Models\CompanyMessage;

class CompanyMessageService
{
    public function getList(int $page, int $pageSize, array $search)
    {
        $builder = CompanyMessage::query();
        if (isset($search['start_date'], $search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['start_date']) && ! isset($search['end_date'])) {
            $builder->where('push_time', '>=', strtotime($search['start_date']));
        }
        if (! isset($search['start_date']) && isset($search['end_date'])) {
            if (strlen($search['end_date']) > 10) {
                $builder->where('push_time', '<=', strtotime($search['end_date']));
            } else {
                $builder->where('push_time', '<=', strtotime($search['end_date']) + (24 * 3600));
            }
        }
        if (isset($search['title'])) {
            $builder->where('title', $search['title']);
        }

        $count = $builder->count();

        $list = $builder->skip(($page - 1) * $pageSize)->take($pageSize)
            ->orderByDesc('id')
            ->get()->toArray();

        return [
            'page' => $page,
            'page_size' => $pageSize,
            'count' => $count,
            'list' => $list,
        ];
    }

    public function create(CompanyMessageFormat $companyMessageFormat)
    {
        $companyMessageFormat->setPushTime(time());
        $companyMessageFormat->setStatus(1);
        CompanyMessage::query()->create($companyMessageFormat->toArrayNotNull());
        return true;
    }

    public function update(CompanyMessageFormat $companyMessageFormat)
    {
        $id = $companyMessageFormat->getId();
        $message = CompanyMessage::query()->find($id);
        if (empty($message)) {
            throw new ApiException('数据不存在', 1);
        }
        $message->update($companyMessageFormat->toArrayNotNull());
        return true;
    }

    public function detail(int $id)
    {
        return CompanyMessage::query()->find($id);
    }

    public function delete(int $id)
    {
        $content = CompanyMessage::query()->find($id);
        if (empty($content)) {
            throw new ApiException('公告不存在', 1);
        }
        $content->delete();
        adminLog(new CompanyMessage(), AdminActionTypeEnum::DELETE, '删除企业公告');
        return true;
    }
}
